<template>
  <!-- <xtx-confirm></xtx-confirm> -->
  <div class="xtx-cart-page">
    <div class="container">
      <xtx-bread>
        <xtx-bread-item to="/">首页</xtx-bread-item>
        <xtx-bread-item>购物车</xtx-bread-item>
      </xtx-bread>
      <div class="cart">
        <table>
          <thead>
            <tr>
              <th width="120">
                <!-- v-model是双向数据绑定，数据影响组件视图，同时改变组件的视图也影响传递的数据，但是我们传递的数据是计算属性，计算属性是允许修改的，计算属性的修改得交给vuex去修改，所以此处不能使用v-model双向绑定，而只需要传递props数据即可 -->
                <xtx-checkbox @change="changeGoodsAllSelected" :modelValue="store.getters['cart/isAll']">全选</xtx-checkbox>
              </th>
              <th width="400">商品信息</th>
              <th width="220">单价</th>
              <th width="180">数量</th>
              <th width="180">小计</th>
              <th width="140">操作</th>
            </tr>
          </thead>
          <!-- 有效商品 -->
          <tbody v-if="store.getters['cart/validList'].length">
            <tr v-for="item  in  store.getters['cart/validList']" :key="item.skuId">
              <!-- 如果函数自身需要传递参数，且还需要接收子组件传递的数据，必须使用$event参数来接收子组件传递的数据 -->
              <td><xtx-checkbox @change="changeGoodsSelected(item, $event)" :modelValue="item.selected" /></td>
              <td>
                <div class="goods">
                  <RouterLink :to="`/product/${item.id}`"><img :src="item.picture" alt=""></RouterLink>
                  <div>
                    <p class="name ellipsis">{{ item.name }}</p>
                    <!-- 选择规格组件 -->
                    <CartSku @change="changeSkuHandle(item.skuId, $event)" :skuId="item.skuId"
                      :attrsText="item.attrsText">
                    </CartSku>
                  </div>
                </div>
              </td>
              <td class="tc">
                <p>&yen;{{ item.nowPrice }}</p>
                <p>比加入时降价 <span class="red">&yen;{{ item.price - item.nowPrice }}</span></p>
              </td>
              <td class="tc">
                <xtx-numbox :max="item.stock" @change="changeGoodsCount(item, $event)" :modelValue="item.count" />
              </td>
              <td class="tc">
                <p class="f16 red">&yen;{{ toFix2(item.nowPrice * item.count) }}</p>
              </td>
              <td class="tc">
                <p><a href="javascript:;">移入收藏夹</a></p>
                <p><a @click="delGoods(item.skuId)" class="green" href="javascript:;">删除</a></p>
                <p><a href="javascript:;">找相似</a></p>
              </td>
            </tr>
          </tbody>
          <!-- 无效商品 -->
          <tbody v-if="store.getters['cart/inValidList'].length">
            <tr>
              <td colspan="6">
                <h3 class="tit">失效商品</h3>
              </td>
            </tr>
            <tr v-for=" item  in  store.getters['cart/inValidList'] " :key="item.skuId">
              <td>
                <xtx-checkbox v-model="item.selected" style="color:#eee;" />
              </td>
              <td>
                <div class="goods">
                  <RouterLink :to="`/product/${item.id}`"><img :src="item.picture" alt=""></RouterLink>
                  <div>
                    <p class="name ellipsis">{{ item.name }}</p>
                    <p class="attr">{{ item.attrsText }}</p>
                  </div>
                </div>
              </td>
              <td class="tc">
                <p>&yen;{{ item.nowPrice }}</p>
              </td>
              <td class="tc">{{ item.count }}</td>
              <td class="tc">
                <p>&yen;{{ item.price }}</p>
              </td>
              <td class="tc">
                <p><a class="green" href="javascript:;">删除</a></p>
                <p><a href="javascript:;">找相似</a></p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          <xtx-checkbox @change="changeGoodsAllSelected" :modelValue="store.getters['cart/isAll']">全选</xtx-checkbox>
          <a @click="batchDeleteCart" href="javascript:;">删除商品</a>
          <a href="javascript:;">移入收藏夹</a>
          <a @click="delInvalidCart" href="javascript:;">清空失效商品</a>
        </div>
        <div class="total">
          共 {{ store.getters['cart/validTotal'] }} 件商品，已选择 {{ store.getters['cart/validSelectedTotal'] }} 件，商品合计：
          <span class="red">¥{{ store.getters['cart/validSelectedAmount'] }}</span>
          <xtx-button @click="goCheckOut" type="primary">下单结算</xtx-button>
        </div>
      </div>
      <!-- 猜你喜欢 -->
      <GoodRelevant />
    </div>
  </div>
</template>
<script setup>
// 同类商品推荐/猜你喜欢
import GoodRelevant from '@/views/product/components/goods-relevant'
import CartSku from './components/cart-sku.vue'
import { useStore } from 'vuex'
import Message from '@/components/library/message'
import Confirm from '@/components/library/confirm'
import { useRouter } from 'vue-router'
const store = useStore()
const router = useRouter()

// 过滤器
function toFix2(value) {
  return value.toFixed(2)
}

// 根据全选的状态更改商品的选中状态
function changeGoodsAllSelected(status) {
  store.dispatch('cart/checkAllCart', status).then(res => {
    Message({ type: 'success', text: '修改成功' })
  }).catch(err => {
    console.log(err.message)
    Message({ type: 'error', text: '修改失败' })
  })
}
// 更改单种类商品的选中状态
function changeGoodsSelected(item, status) {
  item.selected = status
  store.dispatch('cart/updateCart', item).then(res => {
    Message({ type: 'success', text: '修改成功' })
  }).catch(err => {
    console.log(err.message)
    Message({ type: 'error', text: '修改失败' })
  })
}
// 删除商品
function delGoods(skuId) {
  Confirm({ title: '删除提示', text: '您确定要删除吗' }).then(() => {
    store.dispatch('cart/delCart', skuId).then(res => {
      Message({ type: 'success', text: '删除成功' })
    })
  }).catch(err => {
    Message({ type: 'warn', text: err.message })
  })
}
// 批量删除
function batchDeleteCart() {
  Confirm({ title: '删除提示', text: '您确定要删除吗' }).then(() => {
    store.dispatch('cart/batchDeleteCart').then(res => {
      Message({ type: 'success', text: '删除成功' })
    })
  }).catch(err => {
    Message({ type: 'warn', text: err.message })
  })
}
// 清除无效商品
function delInvalidCart() {
  Confirm({ title: '删除提示', text: '您确定要删除吗' }).then(() => {
    store.dispatch('cart/batchDeleteInvalidCart').then(res => {
      Message({ type: 'success', text: '删除成功' })
    })
  }).catch(err => {
    Message({ type: 'warn', text: err.message })
  })
}
// 更改购物车商品的数量
function changeGoodsCount(item, newNum) {
  item.count = newNum
  store.dispatch('cart/updateCart', item).then(res => {
    Message({ type: 'success', text: '修改成功' })
  }).catch(err => {
    Message({ type: 'error', text: err.message })
  })
}
// 修改sku数据
function changeSkuHandle(oldSkuId, sku) {
  console.log(oldSkuId)
  const { skuId, price: nowPrice, oldPrice: price, inventory: stock, specsText: attrsText } = sku
  store.dispatch('cart/updateCartSku', { oldSkuId, sku: { skuId, nowPrice, price, stock, attrsText } })
}
// 去结算
function goCheckOut() {
  // 1. 判断是否选择有效商品
  if (store.getters['cart/validSelectedList'].length === 0) {
    return Message({ type: 'warn', text: '请至少选中一件商品进行结算' })
  }
  // 2. 判断是否已经登录，未登录 弹窗提示
  // 3. 进行跳转 （需要做访问权限控制）
  if (!store.state.user.profile.token) {
    Confirm({ title: '温馨提示', text: '下单结算需要登录，您是否去登录？' }).then(() => {
      // 点击确认
      router.push('/member/checkout')
    })
  } else {
    // 登录了直接去往结算页
    router.push('/member/checkout')
  }
}

</script>
<style scoped lang="less">
.tc {
  text-align: center;

  .xtx-numbox {
    margin: 0 auto;
    width: 120px;
  }
}

.red {
  color: @priceColor;
}

.green {
  color: @xtxColor
}

.f16 {
  font-size: 16px;
}

.goods {
  display: flex;
  align-items: center;

  img {
    width: 100px;
    height: 100px;
  }

  >div {
    width: 280px;
    font-size: 16px;
    padding-left: 10px;

    .attr {
      font-size: 14px;
      color: #999;
    }
  }
}

.action {
  display: flex;
  background: #fff;
  margin-top: 20px;
  height: 80px;
  align-items: center;
  font-size: 16px;
  justify-content: space-between;
  padding: 0 30px;

  .xtx-checkbox {
    color: #999;
  }

  .batch {
    a {
      margin-left: 20px;
    }
  }

  .red {
    font-size: 18px;
    margin-right: 20px;
    font-weight: bold;
  }
}

.tit {
  color: #666;
  font-size: 16px;
  font-weight: normal;
  line-height: 50px;
}

.xtx-cart-page {
  .cart {
    background: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }
}
</style>